<script setup>
import { ref, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { useUserStore } from '@/stores/user.js'
import { LoadingOutlined, UserOutlined, CameraOutlined } from '@ant-design/icons-vue'
import request, { getServerUrl } from '@/utils/request'

const userStore = useUserStore()
const user = ref({
  username: '',
  avatarUrl: '',
  createdTime: '',
  scanCount: 0
})

const loading = ref(true)
const uploadLoading = ref(false)
const avatarUrl = ref('')
const showUploadTip = ref(false)

onMounted(() => {
  // 从pinia存储获取用户数据
  const userData = userStore.user
  if (userData && userData.username) {
    user.value.username = userData.username
    user.value.scanCount = userData.scanCount
    // 处理头像URL
    if (userData.avatarUrl) {
      // 检查avatarUrl是否已经是完整URL
      if (userData.avatarUrl.startsWith('http') || userData.avatarUrl.startsWith('https')) {
        avatarUrl.value = userData.avatarUrl
      } else {
        // 否则拼接服务器地址
        avatarUrl.value = getServerUrl() + userData.avatarUrl
      }
      console.log('设置头像URL:', avatarUrl.value)
    } else {
      avatarUrl.value = ''
    }
    
    user.value.createdTime = formatDate(userData.created_time) || ''
    
    // 获取识别记录数量
    const records = JSON.parse(localStorage.getItem('records') || '[]')
    user.value.identifyCount = records.length
  }
  
  loading.value = false
})

// 格式化日期函数
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  if (isNaN(date.getTime())) return dateString;
  
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  
  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// 头像上传相关函数
const beforeUpload = (file) => {
  // 修正MIME类型检查，jpeg和jpg都是有效类型
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('只能上传JPG/PNG格式图片!')
    return false
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小不能超过2MB!')
    return false
  }
  return isJpgOrPng && isLt2M
}

const getBase64 = (img, callback) => {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result))
  reader.readAsDataURL(img)
}

const handleAvatarChange = (info) => {
  if (info.file.status === 'uploading') {
    uploadLoading.value = true
    return
  }
  
  if (info.file.status === 'done') {
    // 请求完成，服务器返回了响应
    if (info.file.response && info.file.response.code === 200) {
      // 获取图片预览
      getBase64(info.file.originFileObj, (url) => {
        avatarUrl.value = url
        uploadLoading.value = false
      })
    }
  } else if (info.file.status === 'error') {
    // 上传失败
    uploadLoading.value = false
    message.error('头像上传失败，请稍后重试')
  }
}

const customRequest = async ({ file, onSuccess, onError }) => {
  try {
    uploadLoading.value = true
    
    // 创建FormData对象
    const formData = new FormData()
    formData.append('avatar', file)
    
    // 调用API上传头像
    const res = await request.fileUpload('/user/uploadImage', formData)
    console.log('上传头像响应:', res);
    
    if (res.data.code === 200) {
      // 上传成功
      onSuccess('头像修改成功')

      // 如果后端返回了新头像的URL，更新头像
      if (res.data.data) {
        console.log('头像上传成功:', res.data)
        // 使用完整的URL路径
        const fullAvatarUrl = getServerUrl() + res.data.data
        console.log('完整头像URL:', fullAvatarUrl)
        avatarUrl.value = fullAvatarUrl
        updateUserAvatar(res.data.data) // 传递相对路径到数据库
      }
    } else {
      // 上传失败
      console.error('头像上传失败:', res.data.message || '未知错误')
      message.error(res.data.message || '头像上传失败')
      onError(new Error(res.data.message || '头像上传失败'))
    }
  } catch (error) {
    console.error('头像上传异常:', error)
    message.error('头像上传失败，请稍后重试')
    onError(error)
  } finally {
    uploadLoading.value = false
  }
}

const updateUserAvatar = async (url) => {
  console.log('更新头像URL:', url);
  
  // 更新用户数据
  const userData = userStore.user
  const res = await request.post('/user/updateAvatar', {
    avatar: url,
    id: userData.id
  })
  
  if (res.data.code === 200) {
    // 更新store中的用户数据
    userData.avatarUrl = url
    userStore.setUser(userData)
    console.log('更新后的用户数据:', userData);
    
    message.success(res.data.message || '头像更新成功')
    // 然后触发登录状态变化事件
    window.dispatchEvent(new Event('login-state-changed'))
  } else {
    message.error(res.data.message || '头像更新失败')
  }
}

const updatePassword = () => {
  message.success('密码修改功能暂未实现')
}
</script>

<template>
  <div class="profile-container">
    <a-spin :spinning="loading">
      <div class="profile-header">
        <h2 class="page-title">个人资料</h2>
      </div>
      
      <a-card class="user-profile-card" :bordered="false">
        <div class="user-profile-layout">
          <!-- 用户基本信息区域 -->
          <div class="user-info-container">
            <!-- 头像区域 -->
            <div class="avatar-section">
              <div class="avatar-wrapper"
                   @mouseenter="showUploadTip = true"
                   @mouseleave="showUploadTip = false">
                <a-upload
                  name="avatar"
                  :show-upload-list="false"
                  :before-upload="beforeUpload"
                  :custom-request="customRequest"
                  @change="handleAvatarChange"
                >
                  <div class="avatar-content">
                    <div v-if="avatarUrl" class="avatar-image">
                      <img :src="avatarUrl" alt="头像" />
                      <div v-if="uploadLoading" class="loading-overlay">
                        <LoadingOutlined />
                      </div>
                    </div>
                    <div v-else class="avatar-fallback">
                      <LoadingOutlined v-if="uploadLoading" />
                      <UserOutlined v-else />
                    </div>
                    
                    <!-- 悬停时显示上传提示 -->
                    <div class="avatar-overlay" :class="{ 'show': showUploadTip || uploadLoading }">
                      <div class="overlay-content">
                        <CameraOutlined />
                        <span>{{ uploadLoading ? '上传中...' : '更换头像' }}</span>
                      </div>
                    </div>
                  </div>
                </a-upload>
              </div>
            </div>
            
            <!-- 用户名区域 -->
            <div class="username-section">
              <h3>{{ user.username}}</h3>
            </div>
            
            <!-- 用户信息列表 -->
            <div class="user-details">
              <div class="detail-item">
                <span class="detail-label">注册时间:</span>
                <span class="detail-value">{{ user.createdTime || '' }}</span>
              </div>
              <div class="detail-item">
                <span class="detail-label">识别次数:</span>
                <span class="detail-value">{{ user.scanCount || '' }}</span>
              </div>
              <!-- 账号状态已删除 -->
            </div>
            
            <!-- 快捷操作按钮 -->
            <div class="quick-actions">
              <a-button type="primary" @click="$router.push('/identify')" class="action-button">
                开始识别
              </a-button>
              <a-button @click="$router.push('/records')" class="action-button">
                查看记录
              </a-button>
            </div>
          </div>
        </div>
      </a-card>
    </a-spin>
  </div>
</template>

<style scoped>
.profile-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.profile-header {
  margin-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 15px;
}

.page-title {
  font-size: 24px;
  color: #1677ff;
  margin: 0;
  font-weight: 600;
}

.user-profile-card {
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.user-profile-card:hover {
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.user-profile-layout {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.user-info-container {
  padding: 30px;
  background-color: #fff;
  border-radius: 8px;
  text-align: center;
  transition: all 0.3s ease;
}

.avatar-section {
  display: flex;
  justify-content: center;
  margin-bottom: 25px;
}

.avatar-wrapper {
  position: relative;
  width: 120px;
  height: 120px;
  cursor: pointer;
  border-radius: 50%;
  overflow: hidden;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  border: 3px solid #1677ff;
}

.avatar-wrapper:hover {
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
  transform: translateY(-3px);
}

.avatar-content {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-image {
  width: 100%;
  height: 100%;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
}

.avatar-fallback {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background-color: #1677ff;
  color: white;
  font-size: 42px;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.avatar-overlay.show {
  opacity: 1;
}

.overlay-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  color: #fff;
}

.overlay-content .anticon {
  font-size: 24px;
  margin-bottom: 6px;
}

.overlay-content span {
  font-size: 14px;
}

.username-section {
  margin-bottom: 25px;
}

.username-section h3 {
  font-size: 24px;
  font-weight: 600;
  margin: 0 0 8px 0;
  color: #333;
}

.user-badge {
  display: inline-block;
  background-color: #e6f7ff;
  color: #1677ff;
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 12px;
  border-top: 1px solid #f0f0f0;
  padding-top: 20px;
  margin-bottom: 25px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
  border-bottom: 1px solid #f5f5f5;
  transition: all 0.2s ease;
}

.detail-item:hover {
  background-color: #f9f9f9;
  padding-left: 8px;
  padding-right: 8px;
  border-radius: 4px;
}

.detail-label {
  color: #666;
  font-weight: 500;
}

.detail-value {
  color: #333;
  font-weight: 500;
}

/* 删除了.status-active类 */

.quick-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
  margin-top: 20px;
}

.action-button {
  min-width: 100px;
  border-radius: 6px;
  transition: all 0.3s;
}

.action-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.profile-cards-container {
  display: none; /* 隐藏卡片容器 */
}

@media (min-width: 768px) {
  .user-profile-layout {
    flex-direction: row;
    justify-content: center;
  }
  
  .user-info-container {
    width: 400px;
    margin: 0 auto;
  }
}

@media (max-width: 576px) {
  .profile-container {
    padding: 10px;
  }
  
  .user-info-container {
    padding: 20px 15px;
  }
  
  .avatar-wrapper {
    width: 100px;
    height: 100px;
  }
  
  .username-section h3 {
    font-size: 20px;
  }
  
  .quick-actions {
    flex-direction: column;
  }
}
</style>